//
//  ServiceDetailModel.swift
//  ezyform
//
//  Created by MoennigQ on 26/12/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
class ServiceDetailModel: HandyJSON {
    var id: Int = 0
    var serviceID: String {
        return String(id)
    }
    var number: String = ""
    //publisher detail
    var company: String = ""
    var publisher: String = ""
    var publisher_phone: String = ""
    var publisher_email: String = ""
    var created_at: String = "" //publish date
    //Owner detail
    var owner_address = ServiceDetailOwnerAddressModel()
    //job detail
    var title: String = "" //subject
    var status: String = "" //Bid, Scheduled, Started,Finished,Unqualified, Approved
    //是否是installer
    var isInstallerFlag: Bool {
        if self.installer_name == APPConfig.loginInfo.fullName {
            return true
        }
        return false
    }
    //是否可以操作service job
    var canEditJobDetailFlag: Bool {
        var retFlag: Bool = false
        var list = [String]()
        list.append(ServiceJobStatusName.started.rawValue.lowercased())
        list.append(ServiceJobStatusName.unqualified.rawValue.lowercased())
        if list.contains(self.status.lowercased()) && self.isInstallerFlag{
            retFlag = true
        }
        return retFlag
    }
    var budget: String = ""
    var payment_status: String = ""
    var due_date: String = ""
    var scheduler_time: String = ""
    var detail: String = ""
    var note: String = ""
    
    var images = [ServiceDetailImageModel]()
    //assignee
    var installer_name: String = ""
    //offers
    var offers = [ServiceDetailOfferModel]()
    //checklist
    var checklists = [PVDChecklistModel]()
    var localChecklists = [PVDChecklistModel]()
    //for start job
    var arrived_at: String = ""
    //for finish job
    var finished_at: String = ""
    //history list
    var historyList = [ServiceDetailHistoryModel]()
    //deleted at
    var deleted_at: String = ""
    //only check if checklist is modidfied
    var detailModifyFlag: Bool {
        let localChecklist = DBManager.shared.loadAllServiceChecklistData(serviceId: self.serviceID)
        if localChecklist.count > 0 {
            return true
        }
        return false
    }
    //
    func copyAllValuesOfModel(_ newModel: ServiceDetailModel){
        self.id = newModel.id
        self.number = newModel.number
        self.company = newModel.company
        self.publisher = newModel.publisher
        self.publisher_phone = newModel.publisher_phone
        self.publisher_email = newModel.publisher_email
        self.created_at = newModel.created_at
        self.owner_address = newModel.owner_address
        self.title = newModel.title
        self.status = newModel.status
        self.budget = newModel.budget
        self.payment_status = newModel.payment_status
        self.due_date = newModel.due_date
        self.scheduler_time = newModel.scheduler_time
        self.detail = newModel.detail
        self.note = newModel.note
        self.images = newModel.images
        self.installer_name = newModel.installer_name
        self.offers = newModel.offers
        self.checklists = newModel.checklists
        self.arrived_at = newModel.arrived_at
        self.finished_at = newModel.finished_at
        self.historyList = newModel.historyList
        self.deleted_at = newModel.deleted_at
        self.dealAndGetLocalChecklist()
    }
    //MARK: - 触发checklist数据通知
    func broadCastChecklistData(){
        ServiceDetailModelHelper.shared.checklists.onNext(self.checklists)
    }
    //MARK: - 组织checklist数据，且获取本地数据
    func dealAndGetLocalChecklist(){
        //增加image header checklist
        let header = PVDChecklistModel()
        header.title = R.string.localizable.checklisT()//"PRE INSTALLATIONE"
        header.type = ChecklistType.headerWithImage.rawValue
        header.section = .otherChecklist
        self.checklists.insert(header, at: 0)
        //
        //获取本地数据
        self.getLocalCheckList()
        //MARK: - 通知数据更新
        self.broadCastChecklistData()
        ServiceDetailModelHelper.shared.images.onNext(self.images)
    }
    func getLocalCheckList(){
        self.localChecklists.removeAll()
        //*********************取消删除重复的image，防止反复上传，再取消上传，网络不好时，重新上传导致的图片丢失
        //0.先获取原始数据
//        self.localChecklists = DBManager.shared.loadAllServiceChecklistData(serviceId: self.serviceID)
        //1.先处理数据，删除已经上传到服务器，但是本地数据还存在的image
        //        if self.localChecklists.count > 0 {
//        _ = self.localChecklists.map { localChecklist in
//            if localChecklist.type == ChecklistType.Image.rawValue{//图片类型
//                _ = self.checklists.map { serverChecklist in
//                    if localChecklist.id == serverChecklist.id, localChecklist.localAddImages.count > 0 {//相同的checklist
//                        //去除本地图片和server上重复的图片(主要是处理：1.从checklist image list中返回时取消了操作队列，可能存在已经上传但网络回调没有回来的情况。2.Reupload的过程中的取消操作)
//                        _ = localChecklist.localAddImages.map { localImageModel in
//                            _ = serverChecklist.images.map { serverImageModel in
//                                if localImageModel.record_at == serverImageModel.record_at {
//                                    DBManager.shared.deleteChecklistImageData(model: localImageModel)
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
        //        }
        //*********************取消删除重复的image，防止反复上传，再取消上传，网络不好时，重新上传导致的图片丢失
        //2.再重新获取数据
        self.localChecklists = DBManager.shared.loadAllServiceChecklistData(serviceId: self.serviceID)
        //MARK: - 将本地数据附加到pvd_checklist上
        _ = self.localChecklists.map { localChecklist in
            _ = self.checklists.map { serverChecklist in
                if localChecklist.id == serverChecklist.id {//相同的checklist
                    if localChecklist.type == ChecklistType.Bool.rawValue || localChecklist.type == ChecklistType.Text.rawValue{
                        serverChecklist.dbId = localChecklist.dbId
                        serverChecklist.answer = localChecklist.answer
                        serverChecklist.answered_at = localChecklist.answered_at
                    }else if localChecklist.type == ChecklistType.Image.rawValue{//图片类型
                        //0.image 降序排列
                        serverChecklist.images = serverChecklist.images.reversed()
                        //1.删除的数据
                        if localChecklist.localDeletedImages.count > 0{
                            //1.将本地已经删除的服务器上的数据，在返回的images list中删除
                            _ = localChecklist.localDeletedImages.map { localImageModel in
                                if let delIndex = serverChecklist.images.firstIndex(where: {$0.id == localImageModel.id}) {
                                    //不显示已经删除的数据
                                    serverChecklist.images.remove(at: delIndex)
                                    //保存已经删除的数据
                                    serverChecklist.localDeletedImages.append(localImageModel)
                                }
                            }
                        }
                        //2.增加的数据
                        if localChecklist.localAddImages.count > 0 {
                            //1.将图片附加到image list上,将本地数据附加到到最前边
                            _ = localChecklist.localAddImages.map { localImageModel in
                                serverChecklist.images.insert(localImageModel, at: 0)
                            }
                        }
                    }
                }
            }
        }
    }
    required init() {
        
    }
}
